﻿using IdentityServer.Domain.Entities;
using IdentityServer.Domain.IRepositories;
using Microsoft.EntityFrameworkCore;

namespace IdentityServer.Infrastructure.Repositories
{
    public class EmailRepository:IEmailRepository
    {
        private readonly IdDbContext context;
        public EmailRepository(IdDbContext context)
        {
            this.context = context;
        }
        public async Task<bool> UpdateEmailSenderAsync(string email, string code)
        {
            try
            {
                var time = DateTime.Now.AddMinutes(15);
                var list = await  context.EmailCodes.Where(x => x.Email == email ).ToListAsync();
                if(list.Count != 0) 
                {
                    context.EmailCodes.RemoveRange(list);
                }
                await context.EmailCodes.AddAsync(new EmailCode(email, code,time));
                await context.SaveChangesAsync();
                return true;
            }
            catch (Exception)
            {

                return false;
            }
        }

        public async Task<bool> FindEmailSenderAsync(string email, string code)
        {
            try
            {
                var res = await context.EmailCodes.Where(x => x.Email == email && x.Code == code && x.OverTime >= DateTime.Now).FirstOrDefaultAsync();
                if(res != null)
                {
                    context.EmailCodes.Remove(res);
                    await context.SaveChangesAsync();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {

                return false;
            }
        }
    }
}
